package light.mvc.controller.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import light.mvc.controller.base.BaseController;
import light.mvc.page.admin.User;
import light.mvc.page.base.Json;
import light.mvc.page.base.Status;
import light.mvc.page.base.SessionInfo;
import light.mvc.service.admin.ResourceServiceI;
import light.mvc.service.admin.UserServiceI;
import light.mvc.utils.GlobalConstant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin")
public class IndexController extends BaseController {

	@Autowired
	private UserServiceI userService;
	
	@Autowired
	private ResourceServiceI resourceService;

	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO);
		if (sessionInfo != null) {
			return "/index";
		}
		return "/login";
	}
	
	@RequestMapping("/register")
	public String register(HttpServletRequest request) {
		return "/register";
	}

	@ResponseBody
	@RequestMapping("/login")
	public Json login(User user, HttpSession session) {
		String errorMsg = null;
        int errorCode = -1;
        Json j = null;
        
		user = userService.login(user);
		if (user != null) {
			errorCode = 0;
			errorMsg = "登录成功！";
			j = new Json(new Status(errorCode,errorMsg),user);
			
			SessionInfo sessionInfo = new SessionInfo();
			sessionInfo.setId(user.getId());
			sessionInfo.setUsername(user.getUsername());
			sessionInfo.setName(user.getName());
			sessionInfo.setRoleId(user.getRoleId());
			sessionInfo.setRoleName(user.getRoleName());
			sessionInfo.setResourceList(user.getResourceList());
			sessionInfo.setResourceAllList(resourceService.resourceAllList());
			session.setAttribute(GlobalConstant.SESSION_INFO, sessionInfo);
		} else {
			errorMsg = "用户名或密码错误！";
			j = new Json(new Status(errorCode,errorMsg),null);
		}
		
		return j;
	}

	@ResponseBody
	@RequestMapping("/logout")
	public Json logout(HttpServletRequest request,HttpSession session) {
		String errorMsg = "您未登录";
        int errorCode = -1;
        
        if (session != null) {
			session.invalidate();
			errorMsg = "注销成功";
			errorCode = 0;
		}
		
		Json j = new Json(new Status(errorCode,errorMsg),null);
		return j;
	}
}

